package util;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

public class NettyUtil {
    public static ByteBuf getByteBuff(ChannelHandlerContext ctx, String text) {
        // 1. 获取二进制抽象 ByteBuf
        ByteBuf buffer = ctx.alloc().buffer();

        // 2. 准备数据，指定字符串的字符集为 utf-8
        byte[] bytes = text.getBytes(Charset.forName("utf-8"));

        // 3. 填充数据到 ByteBuf
        buffer.writeBytes(bytes);

        return buffer;
    }

    public static String getStringByteBuff(ByteBuf byteBuf) {
        return byteBuf.toString(StandardCharsets.UTF_8);
    }
}
